package com.gzw.scm.wuyong;

import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import com.gzw.scm.DEL.DBManager;
import com.gzw.scm.MyApplication;
import com.gzw.scm.R;
import com.gzw.scm.adapter.ZZXFPAdapter;
import com.gzw.scm.base.BaseActivity;
import com.gzw.scm.bean.Constant;
import com.gzw.scm.utils.HttpUtils;
import com.gzw.scm.utils.T;
import com.gzw.scm.utils.UrlUtils;
import com.gzw.scm.view.SwipeRefreshLayout;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Administrator on 2017/5/2.
 */

public class FCZZXActivity extends BaseActivity {
    private Context mContext;
    private RecyclerView mRecyclerView;
    private Toolbar toolbar;
    private Intent intent;
    private Button btn_sure, btn_delete;
    private TextView tv_seleteAll;
    private boolean isCheck = false;
    private DBManager dbManager;
    private List<String> ls_bh,ls_xzbh;
    private ZZXFPAdapter zzxfpAdapter;
    private ProgressDialog mProgressDialog;
    private SwipeRefreshLayout mSwipeLayout;
    private String eid;
    private String dataType = "fb-fc";

    @Override
    protected void setContentView() {
        setContentView(R.layout.activity_fpzzx);
    }

    @Override
    protected void initViews() {
        toolbar = (Toolbar) findViewById(R.id.toolbar);
        mRecyclerView = (RecyclerView) findViewById(R.id.rv_fp);
        btn_sure = (Button) findViewById(R.id.btn_sure);
        btn_delete = (Button) findViewById(R.id.btn_delete);
        tv_seleteAll = (TextView) findViewById(R.id.ic_head1).findViewById(R.id.tv_selectAll);
    }

    @Override
    protected void initData() {
        mContext = this;
        toolbar.setTitle("周转箱发出");
        setSupportActionBar(toolbar);

        intent = getIntent();
        eid = intent.getStringExtra("eid");

             /*
        * 刷新框架
        * */
        mRecyclerView.setHasFixedSize(true);
        //设置布局管理器
        mRecyclerView.setLayoutManager(new LinearLayoutManager(this));
        //设置Item增加、移除动画
        mRecyclerView.setItemAnimator(new DefaultItemAnimator());
        //添加默认分割线
        mSwipeLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);

        mSwipeLayout.setColor(android.R.color.holo_blue_bright,
                android.R.color.holo_green_light,
                android.R.color.holo_orange_light,
                android.R.color.holo_red_light);
        mSwipeLayout.setMode(SwipeRefreshLayout.Mode.DISABLED);
        mSwipeLayout.setLoadNoFull(false);

        dbManager = new DBManager(mContext);
        ls_bh = new ArrayList<>();
        ls_xzbh = new ArrayList<>();

        setData();
    }

    @Override
    protected void initEvents() {
        toolbar.setNavigationOnClickListener(new myOnClick());
        btn_sure.setOnClickListener(new myOnClick());
        btn_delete.setOnClickListener(new myOnClick());
        tv_seleteAll.setOnClickListener(new myOnClick());
    }

    class myOnClick implements View.OnClickListener {
        @Override
        public void onClick(View v) {
            switch (v.getId()) {
                case R.id.btn_sure:
                    senddata();
                    break;
                case R.id.btn_delete:
                    deleteZzxbh();
                    break;
                case R.id.tv_selectAll:
                    if (ls_bh != null) {
                        if (isCheck == false) {
                            // 遍历list的长度，将MyAdapter中的map值全部设为true
                            for (int i = 0; i < ls_bh.size(); i++) {
                                ZZXFPAdapter.getIsSelected().put(i, true);
                            }
                            zzxfpAdapter.notifyDataSetChanged();
                            //改变状态
                            isCheck = true;
                        } else {
                            // 遍历list的长度，将已选的按钮设为未选
                            for (int i = 0; i < ls_bh.size(); i++) {
                                if (ZZXFPAdapter.getIsSelected().get(i)) {
                                    ZZXFPAdapter.getIsSelected().put(i, false);
                                }
                            }
                            zzxfpAdapter.notifyDataSetChanged();
                            isCheck = false;
                        }
                    }
                    break;
                default:
                    finish();
                    break;
            }
        }
    }

    /**
     * 扫描结果
     */
    @Override
    protected String scanRelust(String code) {
        if (code.indexOf("该二维码不符合规则") > 0) {
            T.showShort(mContext, "该二维码不符合规则");
        } else {
            isScan(code);
        }
        return code;
    }

    ;

    /**
     * 判断是否已扫
     */
    private void isScan(String bh) {
        Boolean isExist = dbManager.IsExistZzxbh(bh, dataType,MyApplication.getUserInfo().getDid());
        if (isExist) {
            T.showShort(mContext, "该二维码已扫描");
        } else {
            dbManager.addZzxbh(bh, dataType,MyApplication.getUserInfo().getDid());
            setData();
        }
    }

    /**
     * 列表赋值
     */
    private void setData() {
        ls_bh.clear();
        List<String> lsbh = dbManager.selectFPZzxbh(dataType,MyApplication.getUserInfo().getDid());
        if (lsbh == null) {
            return;
        } else {
            ls_bh.addAll(lsbh);
        }
        if (ls_bh == null) {
            return;
        }
//        if (mRecyclerView.getAdapter() == null) {
        zzxfpAdapter = new ZZXFPAdapter(ls_bh);
        mRecyclerView.setAdapter(zzxfpAdapter);
//        } else {
//            zzxfpAdapter.notifyDataSetChanged();
//        }
        zzxfpAdapter.setOnRecyclerViewListener(new ZZXFPAdapter.OnRecyclerViewListener() {
            @Override
            public void onItemClick(int position) {
                if (ZZXFPAdapter.getIsSelected().get(position) == true) {
                    ZZXFPAdapter.getIsSelected().put(position, false);
                    zzxfpAdapter.notifyDataSetChanged();
                } else {
                    ZZXFPAdapter.getIsSelected().put(position, true);
                    zzxfpAdapter.notifyDataSetChanged();
                }
            }

            @Override
            public boolean onItemLongClick(int position) {
                return false;
            }
        });

    }

    /**
     * 删除周转箱编号
     */
    private void deleteZzxbh() {
        List<String> lsbh = new ArrayList<>();
        for (int i = 0; i < ls_bh.size(); i++) {
            if (zzxfpAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bh.get(i));
            }
        }
        if (lsbh.size() == 0) {
            T.showShort(mContext, "请先选择要删除的编号!");
        } else {
            showDeleteInfo(lsbh);
        }
    }

    /**
     * 删除数据是的提示框
     */
    private void showDeleteInfo(final List<String> ls_bh) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要删除这"+ls_bh.size()+"个编号吗?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dbManager.deleteFPZzxbh(ls_bh, dataType,MyApplication.getUserInfo().getDid());
                setData();
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }

    /**
     * 上传数据
     */
    private void senddata() {
        List<String> lsbh = new ArrayList<>();
        for (int i = 0; i < ls_bh.size(); i++) {
            if (zzxfpAdapter.getIsSelected().get(i)) {
                lsbh.add(ls_bh.get(i));
            }
        }
        if (lsbh.size() == 0) {
            T.showShort(mContext, "请先选择要分配的编号!");
        } else {
            showSendInfo(lsbh);
        }
    }

    /**
     * 删除数据是的提示框
     */
    private void showSendInfo(final List<String> ls_bh) {
        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setTitle("确定要分配这"+ls_bh.size()+"个周转箱吗?");
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                ls_xzbh.clear();
                ls_xzbh.addAll(ls_bh);
                String idStr = new String();
                for (String str : ls_bh) {
                    idStr = idStr + str + ",";
//                    Log.d("Debug", "onClick: " + idStr);
                }
                idStr = idStr.substring(0, (idStr.length() - 1));

                SendTask sendTask = new SendTask();
                sendTask.execute(idStr);
            }
        });
        builder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
            }
        });
        builder.show();
    }

    /**
     * 上传的数据请求
     */

    public class SendTask extends AsyncTask<String, Void, String> {
        //onPreExecute方法用于在执行后台任务前做一些UI操作
        @Override
        protected void onPreExecute() {
            mProgressDialog = ProgressDialog.show(mContext, null, "正在加载中...");
            mProgressDialog.setCancelable(true);
        }

        protected String doInBackground(String... params) {
            SharedPreferences sharedPreferences = getSharedPreferences(Constant.USERINFO_KEY, Context.MODE_PRIVATE);
            String userId = String.valueOf(sharedPreferences.getInt(Constant.UAER_ID,00000000000));
            String json = "tboxsNo=" + params[0] + "&did=" + MyApplication.getUserInfo().getDid() +
                    "&belongid=" + String.valueOf(MyApplication.getUserInfo().getBelongId()) + "&type=5"
                    + "&userid=" + userId + "&eid=" + eid;
//            Log.d("Debug","doInBackground:"+json);
            return HttpUtils.doPost(UrlUtils.getInstance().getNewJavaUrl("branchOperation.do", "PDABranch"), json);
        }

        @Override
        protected void onPostExecute(final String result) {
            mProgressDialog.dismiss();
            Log.d("Debug", "onPostExecute:"+result);
            if (result == null || result.length() == 0) {
                T.showShort(mContext, "连接服务器异常");
                return;
            }
            if (result.indexOf("true")>=0) {
                T.showShort(mContext, "发出成功");
                dbManager.deleteFPZzxbh(ls_xzbh, dataType,MyApplication.getUserInfo().getDid());
                setData();
            } else if (result.indexOf("系统异常")>=0) {
                T.showShort(mContext, "系统异常");
            } else {
                T.showShort(mContext,result+"失败发出");
                String[] str_Array = result.split(",");
                List<String> ls = new ArrayList<>();
                for (int i = 0; i < str_Array.length; i++) {
                    ls.add(str_Array[i]);
                }
                ls_xzbh.removeAll(ls);
                dbManager.deleteFPZzxbh(ls_xzbh, dataType,MyApplication.getUserInfo().getDid());
                setData();
            }

        }
    }

}